#include "system_init.h"
#include "can_buffer.h"
#include "can_driver.h"

CAN_MSG   CANFIFOBuffer[32];//定义CAN消息缓冲区，深度值必须是2的n次方
CAN_BUFFER  CANRxBuffer[2];

void CAN_BUF_Init(uint8_t Channel)
{
  CANRxBuffer[Channel].BufferSize = 16;
  CANRxBuffer[Channel].pBuffer = CANFIFOBuffer;
  CANRxBuffer[Channel].ReadIndex = 0;
  CANRxBuffer[Channel].WriteIndex = 0;
  CANRxBuffer[Channel].GotMsgNum = 0;
}

//获取当前正在接收数据帧
CAN_MSG *CAN_BUF_PickMsg(uint8_t Channel)
{
  return &CANRxBuffer[Channel].pBuffer[CANRxBuffer[Channel].WriteIndex];
}
//表示成功读取到一帧数据
void CAN_BUF_ApendMsg(uint8_t Channel)
{
	INT_Interrupt_Enable(INT_CAN4,FALSE);
	CANRxBuffer[Channel].WriteIndex = (++CANRxBuffer[Channel].WriteIndex)&(CANRxBuffer[Channel].BufferSize-1);//写缓冲区递增
	//判断缓冲区是否已满
	if(CANRxBuffer[Channel].WriteIndex==CANRxBuffer[Channel].ReadIndex){
	CANRxBuffer[Channel].ReadIndex = (++CANRxBuffer[Channel].ReadIndex)&(CANRxBuffer[Channel].BufferSize-1);//读缓冲区递增
	}else{
	CANRxBuffer[Channel].GotMsgNum++; //有效数据加1
	}
	INT_Interrupt_Enable(INT_CAN4,TRUE);
}

void CAN_BUF_PushMsg(uint8_t Channel,CAN_MSG CANMsg)
{
  CAN_MSG *pMsg = CAN_BUF_PickMsg(Channel);
  *pMsg = CANMsg;
  CAN_BUF_ApendMsg(Channel);
}

//获取成功读到的消息
int CAN_BUF_PopMsg(uint8_t Channel,CAN_MSG **pMsg,uint8_t MsgLen)
{
	INT_Interrupt_Enable(INT_CAN4,FALSE);
	int MsgNum = ((CANRxBuffer[Channel].WriteIndex>=CANRxBuffer[Channel].ReadIndex)?CANRxBuffer[Channel].GotMsgNum:(CANRxBuffer[Channel].BufferSize-CANRxBuffer[Channel].ReadIndex));
	*pMsg = &CANRxBuffer[Channel].pBuffer[CANRxBuffer[Channel].ReadIndex];
	MsgNum = (MsgNum<MsgLen)?MsgNum:MsgLen;//根据需要返回的帧数调整实际返回帧数
	CANRxBuffer[Channel].GotMsgNum -= MsgNum;
	CANRxBuffer[Channel].ReadIndex = (CANRxBuffer[Channel].ReadIndex+MsgNum)&(CANRxBuffer[Channel].BufferSize-1);
	INT_Interrupt_Enable(INT_CAN4,TRUE);
	return MsgNum;
}

